#!/usr/bin/perl -w

# ######################################################### #
# This script can create a tma module from a given tma file #
#                                                           #
# The tma module is used to generate tma files              #
#                                                           #
# elements which would be replaced in this kind of module   #
# is marked by a '$' prefixed key word                      #
# ######################################################### #

use strict;

my ($module, $tma) = @ARGV;

# the path which stores modules
my $MODPATH = "module/";

my %KEYWORDS = (
		'lotid' => ['lot No', 'lotid'],
		'waferid' => ['wafer ID', 'waferid'],
		'totaldie' => ['total test die', 'gross die', 'total die', 'totaldie'],
		'passdie' => ['pass die', 'passdie'],
		'faildie' => ['fail die', 'faildie'],
		'yield' => ['yield']
		);

open(TMA, "< $tma") or die $!;
open(MOD, "> $MODPATH$module") or die $!;

my $field = 1;
while (<TMA>) {
    #chomp;
    
    if (/wafer\s+information/i) {
	$field = 0;
    }

    if ($field == 1) {
	# if it's mapping field
	# replace 'P' or 'F' with '$X'

	s/\b[PF]\b/\$X/g;
    } else {
	# if it's not mapping field
	# split meta information
	
	my ($item, $value) = split(/\s*:\s*/);

	if (defined($item) and defined($value)) {
	    # to find if value is a keyword that should be replaced

	    for my $kw (keys %KEYWORDS) {
		for my $phase (@{$KEYWORDS{$kw}}) {
		    if ($item =~ /$phase/i) {
			s/(:\s*)\S+/$1\$$kw/;
			last;
		    }
		}
	    }

	}
    }

    print MOD "$_";
}
